package tbdp.tool.common;

import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置基类，提供类型转换接口
 *
 * @author xbkaishui
 * @version $Id: Configuration.java, v 0.1 2015-7-23 下午2:38:03 xbkaishui Exp $
 */
public class Configuration {

    /**  */
    protected Map<String, Object> propes;

    /**
     * @param propes
     */
    public Configuration(Map<String, Object> propes) {
        this.propes = propes;
    }

    /**
     *
     */
    public Configuration() {
        propes = new HashMap<String, Object>();
    }

    /**
     *
     * @param key
     * @param val
     * @return
     */
    public boolean put(String key, Object val) {
        if (propes.containsKey(key)) {
            return false;
        }
        propes.put(key, val);
        return true;
    }

    /**
     *
     * @param path
     * @return
     */
    public String getValueAsString(String path) {
        return getValueAsString(path, null);
    }

    /**
     *
     * @param path
     * @param df
     * @return
     */
    public String getValueAsString(String path, String df) {
        Object rt = getValue(path, df);
        if (rt != null) {
            return rt.toString();
        }
        return df;
    }

    /**
     *
     * @param path
     * @return
     */
    public Object getValue(String path) {
        return getValue(path, null);
    }

    /**
     *
     * @param path
     * @param def
     * @return
     */
    public Object getValue(String path, Object def) {
        Object obj = null;
        if (StringUtils.isNotEmpty(path)) {
            obj = propes.get(path);
        }
        if (obj == null) {
            obj = def;
        }
        return obj;
    }


    /**
     *
     * @param path
     * @return
     */
    public Long getValueAsLong(String path) {
        return getValueAsLong(path, null);
    }

    /**
     *
     * @param path
     * @param def
     * @return
     */
    public Long getValueAsLong(String path, Long def) {
        Long rt = null;
        if (!StringUtils.isEmpty(path)) {
            Object obj = getValue(path);
            rt = Long.valueOf((String) obj);
        }
        if (rt == null) {
            rt = def;
        }
        return rt;
    }

    /**
     *
     * @param path
     * @return
     */
    public Double getValueAsDouble(String path) {
        return getValueAsDouble(path, null);
    }

    /**
     *
     * @param path
     * @param def
     * @return
     */
    public Double getValueAsDouble(String path, Double def) {
        Double rt = null;
        if (StringUtils.isNotEmpty(path)) {
            Object obj = getValue(path);
            rt = Double.valueOf((Double) obj);
        }
        if (rt == null) {
            rt = def;
        }
        return rt;
    }
}